import axios from 'axios'
import { getToken } from './auth'
import { Message } from 'element-ui'
axios.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers.get['X-Requested-With'] = 'XMLHttpRequest'


function createSigin() {
  const baseURL = 'https://lovetec.xishuw.com'
  const version = '2.0.8'
  let appId = '3b8c15dc55121ae7681f85a69b0cb401'
  let token = ""
  if (getToken()) {
    token = getToken()
  } else {
    token = ''
  }
  return {
    baseURL,
    version,
    appId,
    token
  }
}

let instance = axios.create({
  baseURL: createSigin().baseURL
})

// 请求拦截
instance.interceptors.request.use(
  config => {
    config.headers.version = createSigin().version
    config.headers.APPID = createSigin().appId
    config.headers.AUTHORIZATION = createSigin().token
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// 响应拦截
instance.interceptors.response.use(
  response => {
    // 'code' : 0, //0 成功  1 失败 2 url跳转  3 执行js  101 提示message 102 登陆失败
    // 当code为 1，显示message统一提示信息
    const errcode = [1, 2, 3, 101, 102]
    let { code, message } = response.data
    if (errcode.includes(code)) {
      Message({
        message: message,
        type: 'error',
        duration: 2000
      })
    }
    return response.data
  },
  err => {
    return Promise.reject(err)
  }
)

export default instance
